package com.punch.order.wxpay.config;


import com.punch.order.wxpay.IWXPayDomain;
import com.punch.order.wxpay.constant.WXPayConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Component
public class WxPayConfig extends AbstractWXPayConfig { // 继承sdk AbstractWXPayConfig 实现sdk中部分抽象方法

    private byte[] certData;

    @Value("${punch.wx.appid}")
    private String appId;

    @Value("${punch.wx.wxPayKey}")
    private String wxPayKey;

    @Value("${punch.wx.mchId}")
    private String wxPayMchId;

    private static WxPayConfig INSTANCE;

    private WxPayConfig() throws Exception {
        // 构造方法读取证书, 通过getCertStream 可以使sdk获取到证书
//        String certPath = "E:\\work\\one-punch-cloud\\punch-business\\order-center\\src\\main\\resources\\oD9B4Fl85b39T3mq.p12";
        String certPath="/opt/jar/order-center/oD9B4Fl85b39T3mq.p12";
        File file = new File(certPath);
//        File file = ResourceUtils.getFile("classpath:apiclient_cert.p12");
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    @Override
    public String getAppID() {
        return appId;
    }

    @Override
    public String getMchID() {
        return wxPayMchId;
    }

    @Override
    public String getKey() {
        return wxPayKey;
    }

    @Override
    public InputStream getCertStream() {
        return new ByteArrayInputStream(this.certData);
    }

    @Override
    public IWXPayDomain getWXPayDomain() { // 这个方法需要这样实现, 否则无法正常初始化WXPay
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }

            @Override
            public DomainInfo getDomain(AbstractWXPayConfig config) {
                return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }
}
